from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ViewSet
from staff.models import *
from management.models import *
from rest_framework.viewsets import ModelViewSet
from utils.ip_address.ip_info import CzIp
from rest_framework.pagination import PageNumberPagination
from .models import *
import redis,json
from .serializer import *

# Create your views here.


# 流程模板
class FlowFlowTemplateSet(ModelViewSet):
    queryset = FlowModel.objects.filter(is_delete=False).all()
    serializer_class = FlowSer

    # 获取流程模板
    def list(self, request, *args, **kwargs):
        try:

            flow_tmp = FlowTemplateModel.objects.filter(is_delete=False).all()
            flow_tmp_list = FlowTemplateSer(flow_tmp, many=True).data
            flow_tmp_ser = json.loads(json.dumps(flow_tmp_list))
            # print("flow>>", flow_tmp_ser)
            # 获取必填节点
            node_need = NodeNeedModel.objects.filter(is_delete=False).all()
            # print("node_need>>", node_need)
            # 获取必填类型
            node_type_list = NeedTypeModel.objects.filter(is_delete=False).all()
            # print("node_type>>", node_type_list)
            # 获取必填选项
            node_option = NeedOptionModel.objects.filter(is_delete=False).all()
            # print("node_opt>>", node_option)

            for i in flow_tmp_ser:
                need = node_need.filter(flow_template_id=i['id']).all()
                need_ser = NodeNeedSer(need, many=True).data
                need_ser = json.loads(json.dumps(need_ser))
                # print('need===================?>', need_ser)
                for n in need_ser:
                    node_type = node_type_list.filter(id=n['type_id']).first()
                    # print('klm==============>', node_type)
                    option = node_option.filter(need_id=n['id'])
                    # print('op==========>', option)
                    option_ser = NeedOptionSer(option, many=True).data
                    option_ser = json.loads(json.dumps(option_ser))
                    # print("option>>+++++++++++++", option_ser)
                    n['type'] = node_type.name
                    n['option'] = option_ser
                i['node_need'] = need_ser

            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取成功！",
                "list": flow_tmp_ser
            })

        except Exception as e:
            print('错误>>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误！{e}"
            })


# 流程视图
class FlowSet(ModelViewSet):
    queryset = FlowModel.objects.all()
    serializer_class = FlowSer
    cz = CzIp()

    # 获取所有流程
    def list(self, request, *args, **kwargs):
        try:
            # 获取所有流程模板
            flow = FlowModel.objects.filter(is_use=True, is_delete=False).all()
            flow_ser = FlowSer(flow, many=True)
            flow_ser_list = json.loads(json.dumps(flow_ser.data))
            print('flow>', flow_ser_list)
            # 获取流程节点
            node_list = NodeModel.objects.filter(is_delete=False).all()
            print('ccc===>', type(node_list))
            for i in flow_ser_list:
                node = node_list.filter(flow_id=i['id']).all()
                node_ser = NodeSer(node, many=True).data
                node_ser_list = json.loads(json.dumps(node_ser))
                print('nodelist===================', node_ser_list)
                i['node'] = node_ser_list

            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取流程成功！",
                "results": flow_ser_list
            })
        except Exception as e:
            print("错误", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 添加流程信息
    def create(self, request, *args, **kwargs):
        staff = request.session.get("staff")
        staff_id = staff.get('id')
        staff_list = request.data.get("staff_list")
        print("staff>>>", staff_list)
        flow_ser = FlowSer(data=request.data)
        if not flow_ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": flow_ser.errors
            })

        flow_ser.save()

        for i in staff_list:
            node_data = {
                "flow_id": flow_ser.data.get("id"),
                "staff_id": i
            }

            node_ser = NodeSer(data=node_data)
            if not node_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": node_ser.errors
                })
            node_ser.save()
        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="添加审批流程操作", staff_id=staff_id, path=f"{method} {path}", ip=ip, address=address, facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "添加流程模板成功！"
        })


# 流程操作
class FlowView(ViewSet):
    cz = CzIp()

    # 删除流程
    def delete(self,request, pk):
        staff = request.session.get("staff")
        staff_id = staff.get('id')
        # 删除流程实例
        new = NewFlowModel.objects.filter(flow_id=pk, status=2).first()
        if new:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "流程正在审批"
            })
        # 删除流程模板
        FlowModel.objects.filter(id=pk,is_delete=False).update(is_delete=True)
        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="删除流程操作", staff_id=staff_id, path=f"{method} {path}", ip=ip, address=address, facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "删除流程成功！"
        })

    # 修改流程
    def update(self, request, pk):
        is_use = request.data.get("is_use")

        flow = FlowModel.objects.filter(id=pk, is_use=True, is_delete=False).first()
        flow_ser = FlowSer(flow).data
        flow_list = json.loads(json.dumps(flow_ser))

        if is_use:
            if is_use == "true":
                flow_list['is_use'] = 1
            else:
                flow_list['is_use'] = 0
        ser = FlowSer(instance=flow,data=flow_list)
        if not ser.is_valid():
            return Response({
                "code": ser.errors
            })
        ser.save()
        return Response({
            "code": status.HTTP_200_OK,
            "message": "修改成功"
        })


# 实例流程实例视图
class NewFlowSet(ModelViewSet):
    queryset = NewFlowModel.objects.all()
    serializer_class = NewFlowSer

    # 获取所有实例流程
    def list(self, request, *args, **kwargs):
        staff = request.session.get("staff")
        staff_id = staff.get("id")
        # 获取流程实例
        new_flow = NewFlowModel.objects.filter(staff_id=staff_id, is_delete=False).all()
        new_flow_ser = NewFlowSer(new_flow, many=True).data
        new_flow_list = json.loads(json.dumps(new_flow_ser))

        # 获取流程模板
        flow_list = FlowModel.objects.filter(is_delete=False).all()

        for i in new_flow_list:
            flow = flow_list.filter(id=i['flow_id']).first()
            i['flow_name'] = flow.name
        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取成功！",
            "results": new_flow_list
        })

    # 添加审批流程
    def create(self, request, *args, **kwargs):
        staff = request.session.get("staff")
        staff_id = staff.get("id")
        flow_id = request.data.get("flow_id")
        need_list = request.data.get("need_list")
        print("数据", flow_id, need_list)
        new_flow = {
            "staff_id": staff_id,
            "flow_id": flow_id
        }
        new_flow_ser = NewFlowSer(data=new_flow)
        if not new_flow_ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": new_flow_ser.errors
            })
        new_flow_ser.save()
        new_flow = json.loads(json.dumps(new_flow_ser.data))
        new_flow_id = new_flow['id']

        for i in need_list:
            new_node_need = {
                "new_flow_id": new_flow_id,
                "need_id": i['need_id'],
                'need': i['need']
            }
            new_node_need_ser = NewNodeNeedSer(data=new_node_need)
            if not new_node_need_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": new_node_need_ser.errors
                })
            new_node_need_ser.save()
        flow = FlowModel.objects.filter(id=flow_id, is_use=True, is_delete=False).first()
        node_list = NodeModel.objects.filter(flow_id=flow.id, is_delete=False).all()

        is_check = False
        for node in node_list:
            if is_check == False:
                is_check = True
                new_node = {
                    "new_flow_id": new_flow_id,
                    "staff_id": node.staff_id,
                    "status": 2,
                }
            else:
                new_node = {
                    "new_flow_id": new_flow_id,
                    "staff_id": node.staff_id,
                }

            new_node_ser = NewNodeSer(data=new_node)
            if not new_node_ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST, "message": new_node_ser.errors})
            new_node_ser.save()

        return Response({"code": status.HTTP_200_OK, "message": "添加成功！", "new_flow": new_flow})


# 审批流程操作
class NewFlowView(ViewSet):
    # 审批流程详情
    def retrieve(self,request, pk):
        staff = request.session.get("staff")
        staff_id = staff.get("id")
        # 获取流程实例
        new_flow = NewFlowModel.objects.filter(id=pk, staff_id=staff_id, is_delete=False).first()
        print('new_flow>>', new_flow)
        new_flow_ser = NewFlowSer(new_flow).data
        new_flow_list = json.loads(json.dumps(new_flow_ser))
        print('new_flo,,', new_flow_list)

        # 流程模板
        flow = FlowModel.objects.filter(id=new_flow_list['flow_id']).first()
        print('flow>>>', flow)
        # 获取节点必填项
        node_need = NodeNeedModel.objects.filter(flow_template_id=flow.flow_tamplate_id).all()
        print('node_need>>', node_need)
        node_need_ser = NodeNeedSer(node_need, many=True).data
        node_need_list = json.loads(json.dumps(node_need_ser))
        for i in node_need_list:
            # 获取节点必填类型
            need_type = NeedTypeModel.objects.filter(id=i['type_id']).first()
            print('need_type>>', need_type)
            # 获取节点必填项选项
            option = NeedOptionModel.objects.filter(need_id=i['id'])
            print('OPtion>>>>>', option)
            option_ser = NeedOptionSer(option, many=True).data
            option_list = json.loads(json.dumps(option_ser))
            i['type'] = need_type.name
            i['option'] = option_list
        new_flow_list['node_need'] = node_need_list
        print('asdasdasdasd===================', new_flow_list)
        # 获取流程节点实例
        new_node = NewNodeModel.objects.filter(new_flow_id=new_flow_list['id'], is_delete=False).all()
        print('new__node==============', new_node)
        new_node_ser = NewNodeSer(new_node, many=True).data
        new_node_list = json.loads(json.dumps(new_node_ser))

        # 获取节点信息
        new_node_need = NewNodeNeedModel.objects.filter(new_flow_id=new_flow_list['id'], is_delete=False).all()
        print('new_node_need=============?', new_node_need)
        new_node_need_ser = NewNodeNeedSer(new_node_need, many=True).data
        new_node_need_list = json.loads(json.dumps(new_node_need_ser))

        new_flow_list['new_node'] = new_node_list
        new_flow_list['new_node_need'] = new_node_need_list

        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取审批流程详情成功!",
            "new_flow":new_flow_list
        })

    # 撤销流程
    def delete(self, request, pk):
        new = NewNodeModel.objects.filter(new_flow_id=pk, status=4).first()
        if new:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "流程正在进行！",
            })
        NewFlowModel.objects.filter(id=pk, is_delete=False).update(status=5)
        NewNodeModel.objects.filter(id=pk, is_delete=False).update(status=5)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "撤销成功！"
        })


# 审批流程信息
class NewNodeAPIView(APIView):
    def get(self,request):
        staff = request.session.get("staff")
        staff_id = staff.get("id")
        print('staff_id', staff_id)
        # 获取流程节点实例
        new_node_data = NewNodeModel.objects.filter(staff_id=staff_id, is_delete=False, status=2).all()
        print('mew_node', new_node_data)
        data = []
        for i in new_node_data:
            # 获取流程实例
            new_flow = NewFlowModel.objects.filter(id=i.new_flow_id, is_delete=False).first()
            new_flow_ser = NewFlowSer(new_flow).data
            new_flow_list = json.loads(json.dumps(new_flow_ser))
            print("new_flow>", new_flow_list)

            # 获取节点信息
            new_node_need = NewNodeNeedModel.objects.filter(new_flow_id=new_flow.id).all()
            new_node_need_ser = NewNodeNeedSer(new_node_need, many=True).data
            new_node_need_list = json.loads(json.dumps(new_node_need_ser))
            print('new_node_need', new_node_need_list)

            # 获取流程节点实例
            new_node = NewNodeModel.objects.filter(new_flow_id=new_flow.id).all()
            new_node_ser = NewNodeSer(new_node, many=True).data
            new_node_list = json.loads(json.dumps(new_node_ser))
            print('new_node', new_node_list)

            new_flow_list["new_node_need"] = new_node_need_list
            new_flow_list["new_node"] = new_node_list
            data.append(new_flow_list)

        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取待审批流程成功！",
            "results": data
        })


# 流程审批
class ApprovalAPIView(APIView):
    # 审批
    def put(self,request,pk):
        remarks = request.data.get("remarks")
        is_pass = request.data.get("is_pass")
        staff = request.session.get("staff")
        staff_id = staff.get("id")

        new_node = NewNodeModel.objects.filter(id=pk,status=2).first()
        new_node_ser = NewNodeSer(new_node).data
        new_node_data = json.loads(json.dumps(new_node_ser))

        if remarks != None:
            new_node_data['remarks'] = remarks
        if is_pass == 'true':
            new_node_data['status'] = 3 # 通过
        else:
            new_node_data['status'] = 4 # 驳回
            new_flow = NewFlowModel.objects.filter(id=new_node.new_flow_id, is_delete=False).first()
            NewFlowModel.objects.filter(id=new_node.new_flow_id, is_delete=False).update(status=4)
            NewNodeModel.objects.filter(new_flow_id=new_flow.id,status=2).update(status=0)

        # 修改节点信息
        new_node_data['staff_id'] = staff_id
        new_node_ser = NewNodeSer(instance=new_node, data=new_node_data)
        if not new_node_ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": new_node_ser.errors
            })
        new_node_ser.save()

        # 修改成功，进行下一节点
        if is_pass == 'true':
            next_new_node = NewNodeModel.objects.filter(new_flow_id=new_node.new_flow_id, status=1).first()
            # 判断是否审批完成
            if next_new_node == None:
                NewFlowModel.objects.filter(id=new_node.new_flow_id, is_delete=False).update(status=3)
            else:
                NewNodeModel.objects.filter(id=next_new_node.id, status=1).update(status=2)

        return Response({
            "code": status.HTTP_200_OK,
            "message": "审批成功！"
        })